package cn.stylefeng.guns.core;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpService {


    private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();;
    /**
     * Post 请求调用
     * @param url
     * @param param
     * @return Map
     */
    public static Map<String,Object> sendHttpPost(String url,Map<String,Object> param){
        Map<String, Object> data = null;
        try {
            String contentstr="";
            String responseStr = "";
            URL myURL = new URL(url);
            HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            httpsConn.setRequestMethod("POST");
            contentstr = gson.toJson(param);
            System.out.println(contentstr);
            OutputStream outputStream = null;
            try {
                outputStream = httpsConn.getOutputStream();
                outputStream.write(contentstr.getBytes("utf-8"));
                outputStream.flush();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
            BufferedReader in = new BufferedReader(insr);
            String inputLine = "";
            StringBuilder result = new StringBuilder();

            while ((inputLine = in.readLine()) != null){
                result.append(inputLine);
                System.out.println(inputLine);
            }
            responseStr = result.toString();
            in.close();
            if(responseStr!=null && responseStr.length()>0){
                data = gson.fromJson(responseStr, Map.class);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

    public static String sendPost(String url,Map<String,Object> param){
        String responseStr = "";
        try {
            String contentstr="";
            URL myURL = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) myURL.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            contentstr = gson.toJson(param);
            System.out.println(contentstr);
            OutputStream outputStream = null;
            try {
                outputStream = httpConn.getOutputStream();
                outputStream.write(contentstr.getBytes("utf-8"));
                outputStream.flush();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            InputStreamReader insr = new InputStreamReader(httpConn.getInputStream());
            BufferedReader in = new BufferedReader(insr);
            String inputLine = "";
            StringBuilder result = new StringBuilder();

            while ((inputLine = in.readLine()) != null){
                result.append(inputLine);
                System.out.println(inputLine);
            }
            responseStr = result.toString();
            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return responseStr;
    }


    /**
     * Get 请求调用
     * @param url
     * @return Map
     */
    public static Map<String,Object> sendHttpGet(String url){
        Map<String, Object> data = null;
        try {
            String responseStr = "";
            URL myURL = new URL(url);
            HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(false);
            httpsConn.setRequestMethod("GET");

            InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
            BufferedReader in = new BufferedReader(insr);
            String inputLine = "";
            StringBuilder result = new StringBuilder();

            while ((inputLine = in.readLine()) != null){
                result.append(inputLine);
                System.out.println(inputLine);
            }
            responseStr = result.toString();
            in.close();
            if(responseStr!=null && responseStr.length()>0){
                data = gson.fromJson(responseStr, Map.class);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

    public static Map<String, Object> sendGet(String url){
        Map<String, Object> data = null;

        try {
            URL myURL = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) myURL.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(false);
            httpConn.setRequestMethod("GET");

            InputStreamReader insr = new InputStreamReader(httpConn.getInputStream());
            BufferedReader in = new BufferedReader(insr);
            String inputLine = "";
            StringBuilder result = new StringBuilder();

            while ((inputLine = in.readLine()) != null){
                result.append(inputLine);
                System.out.println(inputLine);
            }
            String responseStr = result.toString();
            in.close();
            if(responseStr!=null && responseStr.length()>0){
                data = gson.fromJson(responseStr, Map.class);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }




    public static Map<String,Object> sendPost(String url, Map<String, String> paramMap,Map<String,String> header){

        Map<String,Object> rsMap = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
            if(header!=null && header.size()>0){
                header.forEach((k,v)->httpPost.addHeader(k,v));
            }
            httpPost.setConfig(requestConfig);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            if (paramMap != null) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //两种entity设置编码
            //UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams,"UTF-8");
            //StringEntity stringEntity = new StringEntity(content.toString(),"UTF-8");

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs,"utf-8");
            httpPost.setEntity(formEntity);
            // 执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                if(result!=null&& !"".equals(result)){
                    rsMap = JSON.parseObject(result,Map.class);
                }
            }
            // 释放链接
            if(response!=null){
                response.close();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(rsMap);
        return rsMap;

    }


    public static JSONObject sendJsonPost(String url, Map<String, String> header){
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //请求参数转JOSN字符串
        try {
            if(header!=null && header.size()>0){
                header.forEach((k,v)->httpPost.addHeader(k,v));
            }
            HttpResponse response = client.execute(httpPost);
            result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(!"0".equals(result.getString("code"))){
            return JSON.parseObject(result.getString("code"));
        }
        String data = result.getString("data");
        JSONObject jsondata= JSON.parseObject(data);
        return jsondata;
    }



    public static JSONObject doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //设置请求超时时间（各项超时参数具体含义链接）
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)

                .setSocketTimeout(10000)
                .build();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            //给这个请求设置请求配置
            httpGet.setConfig(requestConfig);

            // 执行请求
            response = httpclient.execute(httpGet);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject json = JSONObject.parseObject(resultString);
        String data = json.getString("data");
        JSONObject jsondata= JSON.parseObject(data);
        return jsondata;
    }


}
